<?php

!defined('IN') && exit('Access denied');

$template->addScript('cselector');


$opt = $_REQUEST['opt'];
$allow = array('list','add','modi','getaddress');
$opt = in_array($opt,$allow) ? $opt : $allow['0'];

if (in_array($opt,array('modi','add','getaddress'))) {
    if ($opt == 'getaddress') {
        $address = $_ENV['db']->fetchAll("SELECT * FROM region WHERE `parent_id` = '".(int)$_POST['object_id']."'");
        echo json_encode($address);
        exit;
    } else {
        if ($opt == 'modi') {
            $cr = $_ENV['db']->fetch("SELECT * FROM customer_receive WHERE cr_id = '".(int)$_GET['rid']."'");
            if (!$cr) exit('x');
            $template->cr = $cr;
        }
        if (POST && AJAX) {
            $data = validate();
            switch ($opt) {
                case 'modi':
                    $sql = buildSql($data);
                    $sql = "UPDATE customer_receive {$sql} WHERE cr_id = '".(int)$_GET['rid']."'";
                break;

                case 'add':
                    $data['customer_id'] = $_G['cid'];
                    $sql = buildSql($data);
                    $sql = "INSERT INTO `customer_receive` {$sql}";
                break;
            }

            $_ENV['db']->runSql($sql);

            outputJson(1,'操作成功');
        }
        // 获取地区信息
        $address = $_ENV['db']->fetchAll("SELECT * FROM region WHERE `parent_id` = '0'");
        $template->address = $address;
    }

    $template->my_page = "front/address_modi";
}

if ($opt == 'list') {
    $rlist = $_ENV['db']->fetchAll("SELECT * FROM customer_receive WHERE customer_id = '{$_G['cid']}'");
    $template->rlist = $rlist;
    $template->my_page = 'front/address_list';
}

function validate() {
    $data = getRequests(array('receive_name','address','zip','tel'));

    if (count($data) != 4) {
        outputJson(0,'请补全信息');
    }

    $length = strlen($data['receive_name']);
    if ($length < 1 || $length > 10) {
        outputJson(0,'客户名称长度应该为1到10位字符');
    }

    if (!preg_match('/\d{7}|\d{11}/',$data['tel'])) {
        outputJson(0,'电话号码应为7或11位纯数字，区号和号码间不能有符号');
    }

    if (!preg_match('/^\d+$/',$data['zip']) || strlen($data['zip']) != 6) {
        outputJson(0,'邮编应为6位纯数字');
    }

    if (strlen($data['address']) > 200) {
        outputJson(0,'收货地址不能大于200字节');
    }

    return $data;
}